﻿using DocumentFormat.OpenXml.Lite.Shared;
using DocumentFormat.OpenXml.Lite.Xml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace DocumentFormat.OpenXml.Lite.SpreadsheetML.Excel.WorksheetElements
{
    [XmlRoot("r", Namespace = Constants.ExcelMain)]
    public class RichTextRun : XmlSerializable
    {
        [Optional]
        [XmlElement("rPr", Namespace = Constants.ExcelMain)]
        public RunProperties Properties { get; set; }

        [XmlElement("t", Namespace = Constants.ExcelMain)]
        public SimpleText Text { get; set; }

        public RichTextRun() { }

        /// <summary>
        /// Hint: you cannot add two elements with the same type.
        /// </summary>
        /// <param name="element"></param>
        /// <returns>True, if the list not contains element with the same type. 
        /// False otherwise (in this case the content will be override the old one).</returns>
        public bool AddProperty(IRunProperty element)
        {
            if (Properties == null)
            {
                Properties = new RunProperties();
            }

            var obj = Properties.Properties.FirstOrDefault(e => e.GetType() == element.GetType());
            if (obj != null)
            {
                (obj as IRunProperty).Copy(element);
            }
            else
            {
                Properties.Properties.Add(element);
                return true;
            }

            return false;
        }
    }

    [XmlRoot("rPr", Namespace = Constants.ExcelMain)]
    public class RunProperties : XmlSerializable
    {
        /// <summary>
        /// Hint: you cannot add two elements with the same type.
        /// </summary>
        [Optional]
        [XmlElement("", Namespace = Constants.ExcelMain)]
        public XmlList<IRunProperty> Properties { get; set; }

        public RunProperties()
        {
            Properties = new XmlList<IRunProperty>();
        }
    }
}
